package com.example.subject10mvn.exceptionHandler;


import com.example.subject10mvn.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

//@ControllerAdvice
@Slf4j
public class ValicatedHandler {
    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Result exceptionHandler(Throwable e){
        Result<Object> result=null;
        if(e instanceof MethodArgumentNotValidException){
            List<ObjectError> erros=((MethodArgumentNotValidException) e).getBindingResult ().getAllErrors ();
            String e_str=handleErrors (erros);
            result=Result.builder ().code ("500").message (e_str).build ();
        }else{
            log.error(e.getMessage());
            result=Result.builder ().code ("500").message (e.getMessage ()).build ();
        }
        return result;
    }


    private String handleErrors(List<ObjectError> erros){
        List<String> list=new ArrayList<>();
        for (ObjectError item:erros
        ) {
            list.add (item.getDefaultMessage ());
        }
        return list.toString ().replace ("[","").replace ("]","");
    }
}
